import React, { useRef, useImperativeHandle, forwardRef } from 'react'
import Graph from './components/Graph'
import Coordinate from './components/Coordinate'
import TopButtons from './components/TopButtons'
import BottomButtons from './components/BottomButtons'
import { useMemoizedFn } from 'ahooks'
import styles from './index.module.scss'

const Viewer = (props, ref) => {
  const graphRef = useRef()
  const topButtonsRef = useRef()
  const bottomButtonsRef = useRef()
  const croodRef = useRef()

  const handleButtonClick = useMemoizedFn(arg => graphRef.current.handleButtonClick(arg))

  const setSwitchButtonState = useMemoizedFn(arg => graphRef.current.setSwitchButtonState(arg))

  const setRotate = useMemoizedFn(arg => graphRef.current.setRotate(arg))

  const updateRoomsNumAndLayoutData = useMemoizedFn(arg => graphRef.current.updateRoomsNumAndLayoutData(arg))

  const setButtonLoading = useMemoizedFn(arg => topButtonsRef.current.setButtonLoading(arg))

  const setDisplayState = useMemoizedFn(arg => bottomButtonsRef.current.setDisplayState(arg))

  const autoplan = useMemoizedFn(arg => props.autoplan(arg))

  const setCoord = useMemoizedFn(arg => croodRef.current.setCoord(arg))

  useImperativeHandle(ref, () => ({
    changeCellsDisplay: arg => graphRef.current.changeCellsDisplay(arg),
    getSelectionCellIDs: arg => graphRef.current.getSelectionCellIDs(arg),
    getSelectionCells: arg => graphRef.current.getSelectionCells(arg),
    getOpenings: arg => graphRef.current.getOpenings(arg),
    setIsFather: arg => graphRef.current.setIsFather(arg),
    handleButtonClick: arg => graphRef.current.handleButtonClick(arg),
    setRotate: arg => graphRef.current.setRotate(arg),
    updateRoomsNumAndLayoutData: arg => graphRef.current.updateRoomsNumAndLayoutData(arg)
  }))

  return (
    <div
      className={styles.viewer}
      onContextMenu={e => {
        e.preventDefault()
        e.stopPropagation()
      }}
    >
      <Graph
        ref={graphRef}
        {...props}
        setCoord={setCoord}
        autoplan={autoplan}
        setButtonLoading={setButtonLoading}
        setDisplayState={setDisplayState}
      />
      <TopButtons
        ref={topButtonsRef}
        handleButtonClick={handleButtonClick}
        getDataByUploadButton={props.getDataByUploadButton}
      />
      <BottomButtons
        ref={bottomButtonsRef}
        setSwitchButtonState={setSwitchButtonState}
        setRotate={setRotate}
        setSplitScreenState={props.setSplitScreenState}
        updateRoomsNumAndLayoutData={updateRoomsNumAndLayoutData}
      />
      <Coordinate ref={croodRef} />
    </div>
  )
}

export default forwardRef(Viewer)
